package com.dongss.study.zookeeper;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * Created by dh on 2017/2/27.
 */
public class CreateGroup implements Watcher {

    private static final int SESSION_TIMEOUT=5000;
    private ZooKeeper zk;
    private CountDownLatch connectedSignal=new CountDownLatch(1);

    public void connect(String host) throws Exception{
        zk=new ZooKeeper(host,SESSION_TIMEOUT,this);
        connectedSignal.await();;
    }

    public void process(WatchedEvent event) {
        if(event.getState()== Event.KeeperState.SyncConnected){
            connectedSignal.countDown();
        }
    }

    public void create(String groupName)throws Exception{
        String path="/"+groupName;
        String createdPath=zk.create(path,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("Created "+createdPath);
    }

    public void close()throws Exception{
        zk.close();
    }

    public static void main(String[] args) throws Exception {
        CreateGroup createGroup = new CreateGroup();
        createGroup.connect(args[0]);
        createGroup.create(args[1]);
        createGroup.close();
    }
}
